package com.v1.video.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.v1.video.R;
import com.v1.video.domain.Header;
import com.v1.video.domain.UploadInfo;
import com.v1.video.domain.VideoInfo;
import com.v1.video.domain.VideoStateOfUploadPageInfo;
import com.v1.video.domain.VideoToZhuanmaPageInfo;
import com.v1.video.engine.NetEngine;
import com.v1.video.exception.ServicesException;
import com.v1.video.option.db.PersonalCenterUploadDB;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;

public class UploadingVideoActivity extends BaseActivity {

	private final String TAG = "UploadingVideoActivity";

	/** 标题 */
	TextView text_title;
	private List<UploadInfo> infos = new ArrayList<UploadInfo>();
	UploadVideoAdapter adapter = new UploadVideoAdapter();
	PullToRefreshListView listViewRefresh;
	ListView listViewVideo;
	GetVideoStateAsync taskVideo = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_video);
		// setContentView(R.layout.item_upload_video);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		super.initView();
		text_title = (TextView) findViewById(R.id.tv_title);
		listViewRefresh = (PullToRefreshListView) findViewById(R.id.upload_video_listView);
		listViewRefresh.setScrollingWhileRefreshingEnabled(false);
		listViewRefresh
				.setMode(com.iss.view.pulltorefresh.PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
		listViewVideo = listViewRefresh.getRefreshableView();
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		super.initData();
		text_title.setText(R.string.upload_video_title);
		List<VideoInfo> mVidoList = new ArrayList<VideoInfo>();
		List<Header> listHeaderDb = getUploadOrHistoryData(mVidoList);

		Logger.i(TAG, "mVidoList.size=" + mVidoList.size());

		if (listHeaderDb != null && listHeaderDb.size() > 0) {
			ruseTheAllVideoData(listHeaderDb);
			listViewVideo.setAdapter(adapter);
			// 拿到soruceid，去访问网络，看看哪些能删 ，以知道上传的状态；
			// 访问完后，执行下面的操作
			// 获取soruceId
			String soruceIds = getAllSourceId();
//			new GetVideoStateAsync(soruceIds).execute();
			taskVideo = new GetVideoStateAsync(soruceIds);
			taskVideo.execute();
			// listview设置adapter
		} else {
			// 无视频的页面显示
		}

	}

	private String getAllSourceId() {
		StringBuffer sourceId = new StringBuffer();
		for (int i = 0; i < infos.size(); i++) {
			if(i != 0){
				sourceId.append(",");
			}
			sourceId.append(infos.get(i).getHerder().sourceid);
		}
		String soruceIds = sourceId.toString();
		return soruceIds;
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		super.setListener();
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		listViewRefresh
				.setOnRefreshListener(new OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
//						String label = DateUtils.formatDateTime(
//								getApplicationContext(),
//								System.currentTimeMillis(),
//								DateUtils.FORMAT_SHOW_TIME
//										| DateUtils.FORMAT_SHOW_DATE
//										| DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						// 下拉刷新的操作
						if (taskVideo != null) {
							taskVideo.isCancelled();
							taskVideo = null;
						}
						String soruceIds = getAllSourceId();
						taskVideo = new GetVideoStateAsync(soruceIds);
						taskVideo.execute();
					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						//
					}
				});
	}

	final Handler percentHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if (msg.arg1 != -1) {
					infos.get(msg.arg2).setProgress(msg.arg1);
				} else {
					ToastAlone.showToast(UploadingVideoActivity.this,
							"网络异常，请稍后再传", 1);
					if (threadUploadVideo != null) {
						threadUploadVideo.destroy();
					}
					threadUploadVideo = null;
				}
				
				adapter.notifyDataSetChanged();
				break;
			case 1:
				// ((UploadInfo) info).getHerder().state = "1";
				// Header headerLod = ((UploadInfo) info).getHerder();
				// UploadInfo upInfo = new UploadInfo();
				// Header headerNew = new Header(headerLod);
				// upInfo.setHerder(headerNew);
				// UploadInfo.getInstance().clear();
				// mLstData.set(index, upInfo);
				// notifyDataSetChanged();
				infos.get(msg.arg2).setProgress(100);
				UploadInfo.getInstance().clear();
				// holder.btm.setVisibility(View.GONE);
				infos.get(msg.arg2).getHerder().state = "2";
				// holder.uploading.setText(R.string.upload_txt_zhuanma);
				adapter.notifyDataSetChanged();
				if (threadUploadVideo != null) {
					try {
						threadUploadVideo.destroy();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				threadUploadVideo = null;
				// 通知服务器让服务器去转码未做
				new GetVideoToZhuanma(infos.get(msg.arg2).getHerder(), msg.arg2)
						.execute();
				break;
			}
		}
	};

	class UploadVideoAdapter extends BaseAdapter {
		// private List<UploadInfo> infos;
		private LayoutInflater mInflater;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView != null)
				holder = (ViewHolder) convertView.getTag();
			else {
				holder = new ViewHolder();
				if (mInflater == null) {
					mInflater = LayoutInflater.from(parent.getContext());
				}
				convertView = mInflater.inflate(R.layout.item_upload_video,
						parent, false);
				holder.uploading = (TextView) convertView
						.findViewById(R.id.item_upload_txt_upload);
				holder.progress = (ProgressBar) convertView
						.findViewById(R.id.item_upload_progress);
				holder.uploadingSize = (TextView) convertView
						.findViewById(R.id.item_upload_txt_size);
				holder.icon = (ImageView) convertView
						.findViewById(R.id.item_upload_img_icon);
				// holder.btm = (ImageView)
				// convertView.findViewById(R.id.item_upload_btn_upload);
				holder.layoutBtn = (RelativeLayout) convertView
						.findViewById(R.id.item_upload_img_back);
				holder.uploadingTitle = (TextView) convertView
						.findViewById(R.id.item_upload_txt_title);
				convertView.setTag(holder);
			}

			final int pos = position;
			final UploadInfo info = infos.get(position);
			holder.uploadingTitle.setText(info.getHerder().title);
			if (UploadInfo.getInstance().getHerder() != null
					&& (info.getHerder().sourceid.equals(UploadInfo
							.getInstance().getHerder().sourceid))) {
				holder.progress.setVisibility(View.VISIBLE);
				holder.uploading.setText(R.string.upload_txt_loading);
				holder.progress.setProgress(info.getProgress());
				// if (UploadInfo.getInstance().getPercent() != -1) {
				// holder.btm.setVisibility(View.VISIBLE);
				// if(UploadInfo.getInstance().getPercent() < 100){
				// holder.progress.setProgress(UploadInfo.getInstance()
				// .getPercent());
				// }else{
				// holder.progress.setProgress(100);
				// UploadInfo.getInstance().clear();
				// holder.btm.setVisibility(View.GONE);
				// info.getHerder().state = "1";
				// holder.uploading.setText(R.string.upload_txt_zhuanma);
				// notifyDataSetChanged();
				// }
				//
				// }
				if (threadUploadVideo == null) {
					threadUploadVideo = new ThreadUploadVideo(pos);
					threadUploadVideo.start();
				}

				holder.uploadingSize.setText(UploadInfo.getInstance()
						.getUploadSize()
						+ "M/"
						+ UploadInfo.getInstance().getUploadTotalSize() + "M");
			} else {
				if (UploadInfo.getInstance().getHerder() != null) {
					if (info.getHerder().state.equals("1")
							|| info.getHerder().state.equals("2")) {

						holder.uploading.setText(R.string.upload_txt_zhuanma);
					} else if (info.getHerder().state.equals("3")) {

						holder.uploading
								.setText(R.string.upload_txt_zhuanma_fail);
					} else {
						holder.uploading.setText(R.string.upload_txt_waiting);
					}
				} else {
					if (info.getHerder().state.equals("1")
							|| info.getHerder().state.equals("2")) {
						holder.uploading.setText(R.string.upload_txt_zhuanma);
					} else if (info.getHerder().state.equals("3")) {
						holder.uploading
								.setText(R.string.upload_txt_zhuanma_fail);
					} else {
						holder.uploading.setText(R.string.upload_txt_continue);
					}
				}
				if (info.getHerder().state.equals("1")
						|| info.getHerder().state.equals("2") || info.getHerder().state.equals("3")) {
					holder.uploadingSize.setText(info.getHerder().getUploadTotalSize()+"M" + "/"
						+ info.getHerder().getUploadTotalSize() + "M");
				}else{
					holder.uploadingSize.setText("0M" + "/"
							+ info.getHerder().getUploadTotalSize() + "M");
				}
				holder.uploading.setTextColor(UploadingVideoActivity.this.getResources().getColor(R.color.color_005fff));
				holder.uploading.setText("上传成功");
				holder.progress.setVisibility(View.GONE);
			}

			holder.layoutBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (UploadInfo.getInstance().isUploading()) {
						ToastAlone.showToast(UploadingVideoActivity.this,
								"您还有正在上传的视频，请稍后", 1);
						return;
					}
					if (info.getHerder().state.equals("0")) {
						Header header = ((UploadInfo) info).getHerder();
						UploadInfo.getInstance().startUpload(
								((UploadInfo) info).getHerder().filePath,
								header, UploadingVideoActivity.this);
						notifyDataSetChanged();
					}
				}
			});

			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return infos.get(position);
		}

		@Override
		public int getCount() {
			return infos.size();
		}

		class ViewHolder {
			TextView uploadingTitle;
			TextView uploadingSize;
			TextView uploading;
			ProgressBar progress;
			ImageView icon;
			RelativeLayout layoutBtn;
			// ImageView btm;
		}
	}

	/**
	 * 融合上传的视频，及转码中的视频和服务器给的已转码完的视频
	 * 
	 * @param listHeaderDb
	 * @param mVidoList
	 * @param strSourceId
	 */
	private void ruseTheAllVideoData(List<Header> listHeaderDb) {

		for (int i = 0; i < listHeaderDb.size(); i++) {
			Header header = listHeaderDb.get(i);
			boolean isSame = false;
			UploadInfo upInfo = new UploadInfo();
			upInfo.setHerder(header);
			infos.add(upInfo);
			if(header.state.equals("2")){
				new GetVideoToZhuanma(header, i);
			}
		}
		
	}

	private List<Header> getUploadOrHistoryData(List<VideoInfo> mVidoList) {
		List<Header> listHeaderDb;
		String strSourceId = "";
		// // if (mCurPage == 0) {
		// Logger.i(TAG, "此处执行了，将要获取正在上传的数据");
		// if (UploadInfo.getInstance().isUploading()) {
		// // if (UploadInfo.getInstance().getHerder().related_Video_Id
		// // .equals(SaveShareActivity2.fromNormal)) {
		// Logger.i(TAG, "存在正在上传的数据");
		// mVidoList.add(UploadInfo.getInstance());
		// strSourceId = UploadInfo.getInstance().getHerder().sourceid;
		// // }
		// }else{
		// Logger.i(TAG, "!UploadInfo.getInstance().isUploading()");
		// }

		listHeaderDb = getListHeaderDb(strSourceId);
		// } else {
		// listHeaderDb = new ArrayList<Header>();
		// Logger.i(TAG, "不获取正在上传的数据");
		// }

		return listHeaderDb;
	}

	private String getUploadSourceId() {
		String strSourceId = "";
		if (UploadInfo.getInstance().isUploading()) {
			// if (UploadInfo.getInstance().getHerder().related_Video_Id
			// .equals(SaveShareActivity2.fromNormal)) {
			strSourceId = UploadInfo.getInstance().getHerder().sourceid;
			// }
		}
		return strSourceId;
	}

	@SuppressWarnings("static-access")
	private List<Header> getListHeaderDb(String strSourceId) {
		List<Header> listHeaderDb;
		listHeaderDb = PersonalCenterUploadDB.getInstance(
				UploadingVideoActivity.this).getUploadInfos(
				UploadingVideoActivity.this);
		if (listHeaderDb != null) {
			Logger.i(TAG, "listHeaderDb.size==" + listHeaderDb.size());
			if (listHeaderDb.size() > 0) {
				List<Header> listTemp = new ArrayList<Header>();
				for (int i = 0; i < listHeaderDb.size(); i++) {
					Header head = listHeaderDb.get(i);
					Logger.i(TAG, "head.scenario=" + head.scenario);
					// if (head.related_Video_Id
					// .equals(SaveShareActivity2.fromNormal)) {
					if (head.state.equals("0")) {
						listTemp.add(head);

						// }
					}
				}
				for (int i = 0; i < listHeaderDb.size(); i++) {
					Header head = listHeaderDb.get(i);
					// if (head.related_Video_Id
					// .equals(SaveShareActivity2.fromNormal)) {
					if (!head.state.equals("0")) {
						listTemp.add(head);
					}
					// }
				}
				listHeaderDb.clear();
				listHeaderDb = null;
				listHeaderDb = listTemp;
				listTemp = null;
			}
			// if (listHeaderDb.size() > 0 && !strSourceId.equals("")) {
			// for (int i = 0; i < listHeaderDb.size(); i++) {
			// Header header = listHeaderDb.get(i);
			// if (strSourceId.equals(header.sourceid)) {
			// listHeaderDb.remove(i);
			// break;
			// }
			// }
			// }
		}
		return listHeaderDb;
	}

	private class GetVideoToZhuanma extends AsyncTask<Void, Void, Boolean> {

		private String errorMsg = "";
		private Header header = null;
		VideoToZhuanmaPageInfo resultInfo;
		private int pos;

		private GetVideoToZhuanma(Header header, int pos) {
			this.header = header;
			this.pos = pos;
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				NetEngine engine = new NetEngine();
				resultInfo = engine.setVideoToZhuanMa(header);
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (errorMsg.equals("")) {
				if (resultInfo.getCode() != 1) {
					ToastAlone.showToast(UploadingVideoActivity.this,
							resultInfo.getMsg(), 1);
					// 转变存储状态，上传成功 ，未转码
					infos.get(pos).getHerder().state = "2";
					PersonalCenterUploadDB.getInstance(
							UploadingVideoActivity.this).updataUploadInfo(
							header, UploadingVideoActivity.this);
				} else {
					// 转变存储状态，转码中
					infos.get(pos).getHerder().state = "1";
					PersonalCenterUploadDB.getInstance(
							UploadingVideoActivity.this).updataUploadInfo(
							header, UploadingVideoActivity.this);
				}
			} else {
				// ToastAlone.showToast(UploadingVideoActivity.this, errorMsg,
				// 1);
			}
		}
	}

	/**
	 * 获取转码状态
	 */
	private class GetVideoStateAsync extends AsyncTask<Void, Void, Boolean> {

		private String errorMsg = "";

		// private ProgressDialog pd;
		VideoStateOfUploadPageInfo resultInfo = null;
		String soruceIds = "";

		public GetVideoStateAsync(String soruceIds) {
			this.soruceIds = soruceIds;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// pd =
			// Utils.getProgressDialog(UploadingVideoActivity.this,getResources().getString(R.string.get_data),
			// this);
			// pd.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				NetEngine engine = new NetEngine();
				resultInfo = engine.getVideoStateOfUpload(soruceIds);
			} catch (ServicesException e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return false;

		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			// if(pd != null && pd.isShowing()){
			// pd.cancel();
			// }
			try {
				if (errorMsg.equals("")) {
					if (resultInfo.getCode() == 1) {
						if (resultInfo.getObj() != null)
							for (int i = 0; i < resultInfo.getObj().size(); i++) {
								if (resultInfo.getObj().get(i).getStatus() == 1) {
									for (int j = 0; j < infos.size(); j++) {
										if (infos.get(j).getHerder().sourceid
												.equals(resultInfo.getObj()
														.get(i).getSourceId())) {
											PersonalCenterUploadDB
											.getInstance(
													UploadingVideoActivity.this)
											.deleteUploadInfo(
													infos.get(j)
															.getHerder(),
													UploadingVideoActivity.this);// 本地数据库去掉
											infos.remove(j);
											break;
										}
									}
								}
							}
						for (int i = 0; i < resultInfo.getObj().size(); i++) {
							if (resultInfo.getObj().get(i).getStatus() == 2) {
								for (int j = 0; j < infos.size(); j++) {
									if (infos.get(j).getHerder().sourceid
											.equals(resultInfo.getObj().get(i)
													.getSourceId())) {
										infos.get(j).getHerder().state = "3";
										// 更新数据库
										PersonalCenterUploadDB
												.getInstance(
														UploadingVideoActivity.this)
												.updataUploadInfo(
														infos.get(j)
																.getHerder(),
														UploadingVideoActivity.this);
										break;
									}
								}
							}
						}
						if (adapter != null) {
							adapter.notifyDataSetChanged();
						}

					} else {
						ToastAlone.showToast(UploadingVideoActivity.this,
								resultInfo.getMsg(), 1);
					}
				} else {
					// ToastAlone.showToast(UploadingVideoActivity.this,
					// errorMsg, 1);
				}
				if (listViewRefresh != null) {
					listViewRefresh.onRefreshComplete();
				}
			} catch (Exception e) {
			}
		}
	}

	ThreadUploadVideo threadUploadVideo = null;

	class ThreadUploadVideo extends Thread {

		public int pos;

		public ThreadUploadVideo(int pos) {
			this.pos = pos;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			while (UploadInfo.getInstance().getPercent() < 100) {
				// Logger.i(TAG,
				// "UploadInfo.getInstance().getPercent()="+UploadInfo.getInstance().getPercent());
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message msg = new Message();
				msg.what = 0;
				msg.arg2 = pos;
				if (UploadInfo.getInstance().getPercent() != -1) {
					msg.arg1 = UploadInfo.getInstance().getPercent();
				} else {
					msg.arg1 = -1;
					break;
				}

				percentHandler.sendMessage(msg);
			}
			Message msg1 = new Message();
			msg1.what = 1;
			percentHandler.sendMessage(msg1);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (taskVideo != null) {
			taskVideo.isCancelled();
			taskVideo = null;
		}
		taskVideo = null;
	}

}
